import axios, {
  AxiosError,
  AxiosInstance,
  AxiosRequestConfig,
  AxiosResponse,
} from "axios";

type Result = {
  data: any;
  state: string;
  message: string;
  success: boolean;
};
// 创建一个 Axios 实例
const axiosInstance: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API, // 设置基础 API URL
  timeout: 5000, // 请求超时时间
  headers: { "Content-Type": "application/json;charset=utf-8" }, // 设置请求头
});

axiosInstance.interceptors.request.use((config) => {
  return config;
});

axiosInstance.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    return handleError(error);
  }
);

const handleError = (error: AxiosError<Result>) => {
  const { response, message } = error || {};
  const errMsg = response?.data?.message || message;
  console.log(errMsg);

  return Promise.reject(errMsg);
};

class service {
  get<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.request("GET", config);
  }
  post<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.request("POST", config);
  }

  request<T = any>(
    method: "GET" | "POST" | "PUT" | "DELETE",
    config?: AxiosRequestConfig
  ): Promise<T> {
    return axiosInstance
      .request<any, AxiosResponse<Result>>({ ...config, method })
      .then((res: AxiosResponse<Result>) => res as unknown as Promise<T>) // 解析成功的响应
      .catch(handleError); // 处理错误
  }
}
export default new service(); // 导出 Axios 实例
